package mi.top.utils;

import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.StrUtil;
import org.eclipse.paho.client.mqttv3.*;

/**
 * @author 祥霸
 * @date 2021.07.13
 */
public class MqttUtils {

    private String productKey;
    private String deviceName;
    private String deviceSecret;

    private MqttClient sampleClient;

    /**
     * productKey: a17TbqVrJir
     * deviceName: test395-1
     * deviceSecret: fce4d48e836ec6fdbfb456c95989bc13
     */
    public MqttUtils(String productKey, String deviceName, String deviceSecret) throws MqttException {
        this.productKey = productKey;
        this.deviceName = deviceName;
        this.deviceSecret = deviceSecret;

        init(sign());
    }

    public MqttSign sign() {

        // 计算MQTT连接参数。
        MqttSign sign = new MqttSign();
        sign.calculate(productKey, deviceName, deviceSecret);

        System.out.println("username: " + sign.getUsername());
        System.out.println("password: " + sign.getPassword());
        System.out.println("clientid: " + sign.getClientid());

        return sign;
    }

    public void init(MqttSign sign) throws MqttException {
        //接入物联网平台的域名。
        String port = "443";
        String broker = "ssl://" + productKey + ".iot-as-mqtt.cn-shanghai.aliyuncs.com" + ":" + port;
        // Paho MQTT客户端。
        sampleClient = new MqttClient(broker, sign.getClientid());
        // Paho MQTT连接参数。
        MqttConnectOptions connOpts = new MqttConnectOptions();
        connOpts.setCleanSession(true);
        connOpts.setKeepAliveInterval(180);
        connOpts.setUserName(sign.getUsername());
        connOpts.setPassword(sign.getPassword().toCharArray());
        sampleClient.connect(connOpts);
        System.out.println("Broker: " + broker + " Connected");
    }


    /**
     * 订阅消息
     */
    public void subscribe(final CallBack callBack) throws MqttException {
        String topic = "/sys/"+productKey+"/"+deviceName+"/thing/model/down_raw";

        sampleClient.subscribe(topic, new IMqttMessageListener() {

            @Override
            public void messageArrived(String s, MqttMessage mqttMessage){
                System.out.println("subscribe:messageArrived");
                System.out.println(s);

                String str = HexUtil.encodeHexStr(mqttMessage.getPayload());
                System.out.println("messageArrived:" + str);
                callBack.msg(str);
            }
        });
    }

    /**
     * 发布消息
     * eg: 01100010000501CF
     */
    public void publish(String hex) throws MqttException {
        String topic = "/sys/"+productKey+"/"+deviceName+"/thing/model/up_raw";

        MqttMessage mqttMessage = new MqttMessage();
        mqttMessage.setQos(0);

        // ack
        mqttMessage.setPayload(HexUtil.decodeHex(hex));

        sampleClient.publish(topic,mqttMessage);
    }

}
